package interfaces.clients.authorization;

import interfaces.clients.authorization.exceptions.MaximallyPossibleQuantityOfTheUsersException;

import java.util.HashMap;
import java.util.TreeSet;

/**
 * The class implements the users database.
 *
 * @author Manujov Maxim
 */
public final class UsersDataBase extends HashMap implements IUsersDataBase {
  /**
   * Constructor
   */
  public UsersDataBase() {
    super();
    ids = new TreeSet();
  }

  /**
   * The variable stores the identificators of the users
   */
  private final TreeSet ids;

  /**
   * The function generates the id for new user.
   *
   * @throws MaximallyPossibleQuantityOfTheUsersException if the quantity of the users is maximally possible
   * @return new id
   */
  public final int makeNewId() throws MaximallyPossibleQuantityOfTheUsersException {
    for (int i = 1; i < Integer.MAX_VALUE; i++) {
      if (!ids.contains(new Integer(i))) return i;
    }
    throw new MaximallyPossibleQuantityOfTheUsersException("The quantity of the users is maximally possible.");
  }

  /**
   * Overrides the method put of class HashMap<K,V>, adds the user id to variable "ids".
   *
   * @param key key
   * @param value value
   * @return user data
   */
  public final UserData put(String key, UserData value) {
    ids.add(new Integer(value.getId()));
    return (UserData)super.put(key, value);
  }

  /**
   * Overrides the method remove of class HashMap<K,V>, removes the user id from variable "ids".
   *
   * @param key key
   * @return user data
   */
  public final Object remove(Object key) {
    ids.remove(new Integer(((UserData)get(key)).getId()));
    return super.remove(key);
  }
}
